package com.epoint.springsecuritylearning.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.epoint.springsecuritylearning.exception.LoginUserDetails;
import com.epoint.springsecuritylearning.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Security的过滤器，用于判断用户是否是登录状态
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        String requestURI = request.getRequestURI();

        System.out.println(requestURI);

        // 1.判断请求头里是否带了TOKEN
        String token = JwtUtil.getToken(request);
        if(StringUtils.isBlank(token)){
            /**
             * 此处不需要抛异常了， 因为 这个过滤器如果不把 Authentication塞入SecurityContext中的话，会被其他Security的过滤器拦截到 然后403
             * 所以直接放行即可
             */
            filterChain.doFilter(request, response);
            return;
//            throw new RuntimeException("用户未登录!");
        }

        // 2.拿着token去redis里查，看有没有，有则登录状态，没有的话 需要让用户去登录
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            filterChain.doFilter(request, response);
            return;
        }
        String userId = claims.getSubject();
        String LoginUser_STR = stringRedisTemplate.opsForValue().get("login:" + userId);
        if(StringUtils.isBlank(LoginUser_STR)){
            filterChain.doFilter(request, response);
            return;
        }

        LoginUserDetails loginUser = JSON.parseObject(LoginUser_STR, new TypeReference<LoginUserDetails>(){});
        // 2.如果有，则去将Security里面流转的Authentication塞入SecurityContextHolder的Context里
        if(loginUser != null){
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request, response);
    }
}
